package demo13;

import java.io.IOException;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Socket;
import java.net.SocketException;

public class UdpEchoServer {

    DatagramSocket socket=null;
    UdpEchoServer(int port) throws SocketException {
        socket=new DatagramSocket(port);
    }

    public void start() throws IOException {
        while(true) {
            DatagramPacket packet = new DatagramPacket(new byte[4096], 4096);
            socket.receive(packet);
            String request = new String(packet.getData(), 0, packet.getLength());
            String respond = process(request);
            DatagramPacket datagramPacket = new DatagramPacket(respond.getBytes(), respond.getBytes().length,
                    packet.getSocketAddress());
            socket.send(datagramPacket);

            System.out.printf("[%s:%d] req=%s, resp=%s\n", packet.getAddress().toString(),
                    packet.getPort(), request, respond);
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server=new UdpEchoServer(9090);
        server.start();
    }
}
